﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Caltrain.View
{
    public static class ListBoxItemBehavior
    {
        #region IsScrollIntoViewWhenSelected

        public static bool GetIsScrollIntoViewWhenSelected(ListBoxItem listBoxItem)
        {
            return (bool)listBoxItem.GetValue(IsScrollIntoViewWhenSelectedProperty);
        }

        public static void SetIsScrollIntoViewWhenSelected(
          ListBoxItem listBoxItem, bool value)
        {
            listBoxItem.SetValue(IsScrollIntoViewWhenSelectedProperty, value);
        }

        public static readonly DependencyProperty IsScrollIntoViewWhenSelectedProperty =
            DependencyProperty.RegisterAttached(
            "IsScrollIntoViewWhenSelected",
            typeof(bool),
            typeof(ListBoxItemBehavior),
            new PropertyMetadata(false, OnIsScrollIntoViewWhenSelectedChanged));

        static void OnIsScrollIntoViewWhenSelectedChanged(
          DependencyObject depObj, DependencyPropertyChangedEventArgs e)
        {
            ListBoxItem item = depObj as ListBoxItem;
            if (item == null)
                return;

            if (e.NewValue is bool == false)
                return;

            if ((bool)e.NewValue)
                ((ListBox)item.Parent).SelectionChanged += OnListBoxItemSelected;
            else
                ((ListBox)item.Parent).SelectionChanged -= OnListBoxItemSelected;
        }

        static void OnListBoxItemSelected(object sender, RoutedEventArgs e)
        {
            // Only react to the Selected event raised by the TreeViewItem
            // whose IsSelected property was modified. Ignore all ancestors
            // who are merely reporting that a descendant's Selected fired.
            if (!Object.ReferenceEquals(sender, e.OriginalSource))
                return;

            ListBoxItem item = e.OriginalSource as ListBoxItem;
            if (item != null)
                ((ListBox)(item.Parent)).ScrollIntoView(item);
        }

        #endregion // IsScrollIntoViewWhenSelected
    }
}
